<?php

namespace app\admin\controller\order;

use app\common\library\Auth;
use app\common\controller\Backend;
use think\Db;
use fast\Random;

/**
 * 订单管理
 *
 * @icon fa fa-user
 */
class Order extends Backend
{
    /**
     * Order模型对象
     * @var \app\admin\model\shop\Order
     */
    protected $model = null;

    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'order_id';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\shop\Order;
        $this->view->assign("orderStateList", $this->model->getOrderStateList());
        $this->view->assign("flagList", $this->model->getFlagList());
        $this->view->assign("roomList", $this->model->getRoomList());
        $this->view->assign("authorStatusList", $this->model->getAuthorStatusList());
    }
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $join[] = ["sd_shop_task k","k.task_id = o.task_id ","left"];//任务表

            $join[] = ["sd_admin n","n.id = o.shop_admin_id","left"];//管理员表

            $join[] = ["sd_user r","r.uid = o.uid","left"];//用户表

            $join[] = ["sd_admin a","a.id = o.author","left"];//管理员


            $field = "o.*,order_id as id";//订单字段

            $field .= ",k.task_sno";//任务


            $field .= ",r.username as rusername";//用户表

            $field .= ",n.username as nusername";//管理员表


            $field .= ",a.username as ausername";//管理员表



            $total = $this->model
                ->alias("o")
                ->join($join)
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->alias("o")
                ->join($join)

//                ->with(['task'=>function($q){
//                    $q->with(['shop','admin']);
//                },'user','admin'])
                //->field('*,order_id as id')
                    ->field($field)
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();

            foreach ($list as &$value){

                $value["r.username"] = $value["rusername"];
                $value["n.username"] = $value["nusername"];
                $value["a.username"] = $value["ausername"];
                $value["o.status"] = $value["status"];

            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 插旗,详情
     */
    public function edit($ids = NULL){
        $row = $this->model
            ->with(['task'=>function($q){
                $q->with('shop');
            },'user','admin','order_image','review','praise'])
            ->field('*,order_id as id')
            ->where("order_id",$ids)
            ->find();

        //halt($row->toArray());
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params) {

                if($params["type"]==1){
                    $this->model->save(["flag_remarks"=>$params["flag_remarks"],"flag"=>"2","flag_time"=>time(),"update_time"=>time()],["order_id"=>$params["order_id"]]);
                }

            }

        }
        $this->view->assign("row", $row);
        $this->view->assign("type",input("type"));
        return $this->view->fetch();
    }


    /**
     *
     * 审核，驳回，催付，撤销，回收
     *
     * method:1
     *
     * 审核
     *
     * method:2
     *
     * 驳回
     *
     * method:3
     *
     * 催付（对派客操作）
     *
     * method:4
     *
     * 撤销
     *
     * method:5
     *
     * 回收
     *
     *
     *
     */
    public function update_status(){

        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params)
            {
                $row = $params["row"];
                //$status = $row["status"];
                $order_id = $row["order_id"];
                //$order_state = $row["order_state"];//订单状态

                //查询数据库的状态
                $order_info = Db::name("shop_order")->where("order_id",$order_id)->find();

                $status = $order_info["status"];//状态

                $order_state = $order_info["order_state"];//订单状态




                //可审核的数组
                $examReject_arr = [1,3,6,10,12];
                switch ($params["method"]){

                    case 1://审核



                        //审核,驳回:status:1,3,6,10,12(可审核) 且还需要 订单状态是正常或者已驳回才可以往下走
                        if(!in_array($status,$examReject_arr) || $order_state==1){
                            renderJson("该状态不可以审核",0);
                        }

                        $res = $this->model->examReject($order_id,$status,1);

                        if($res) {
                            renderJson("审核成功", 1);
                        }
                        break;

                    case 2://驳回
                        //审核,驳回:status:1,3,6,10,12(可审核) 且还需要 订单状态是正常或者已驳回才可以往下走
                        if(!in_array($status,$examReject_arr) || $order_state==1 ){
                            renderJson("该状态不可以审核",0);
                        }
                        $res = $this->model->examReject($order_id,$status,2);

                        if($res) {
                            renderJson("审核成功", 1);
                        }
                        break;

                    case 3://催付（对派客操作）

                        $uid = $params["uid"];
                        $username = Db::name("user")->where("uid",$uid)->value("username");
                        $openid = Db::name("wx_users")->where("uid",$uid)->value("openid");
                        $time = date("Y-m-d H:i:s",(time()+7200));
                        //$flag   = $params["bank_name"]."-".$params["bank_no"]."-".$params["cash"]."元";
                        $content = [
                            $username,$row["goods_sno"],$time
                        ];
                        $msg = [
                            "condition"=>13,
                            "touser"=>$openid,
                            "content"=>$content
                        ];
                        $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                        $MiniMsg->sendMsg();//发送短信模板催款成功

                        break;

                    case 4://撤销
                        //可撤销组合状态
                        $cancle_arr = [1,2,3,4,5,6,7,8,9,10,11,12];
                        if(!in_array($status,$cancle_arr)){
                            renderJson("该状态不可以撤销",0);
                        }
                        //
                        $res = $this->model->save(["order_state"=>1,"update_time"=>time()],["order_id"=>$order_id]);

                        if($res){

                            renderJson("撤销成功", 1);
                        }

                        break;


                    case 5://回收

                        //订单状态为1的时候才可以回收
                        if($order_state!=1){
                            renderJson("该状态不可以回收",0);
                        }

                        $res = $this->model->save(["order_state"=>2,"update_time"=>time()],["order_id"=>$order_id]);

                        if($res){

                            renderJson("回收成功", 1);
                        }

                        break;


                    case 6://编辑



                        break;

                }
            }
        }
    }



    /**
     * 批量撤销订单
     */
    public function mult_cancel(){

        $pass = input("post.");

        $ids = [];

        if($pass["ids"]) {

            foreach ($pass["ids"] as $k => $v) {
                $ids[] = $v["id"];
            }
            $cancle_arr = [1,2,3,4,5,6,7,8,9,10,11,12];
            Db::name("shop_order")->where("order_id", "in", $ids)->where("status","in",$cancle_arr)->update(["status" => 1,"update_time"=>time()]);
            renderJson("成功撤销", 1);
        }else{

            renderJson("请勾选你的选项", 0);
        }


    }



    /**
     * 批量回收订单
     */
    public function mult_back(){

        $pass = input("post.");

        $ids = [];

        if($pass["ids"]) {

            foreach ($pass["ids"] as $k => $v) {
                $ids[] = $v["id"];
            }
            $cancle_arr = [1,2,3,4,5,6,7,8,9,10,11,12];
            Db::name("shop_order")->where("order_id", "in", $ids)->where("status","in",$cancle_arr)->update(["status" => 2,"update_time"=>time()]);
            renderJson("成功回收", 1);
        }else{

            renderJson("请勾选你的选项", 0);
        }


    }



    /**
     * 批量催付
     */
    public function mult_pay(){


        $pass = input("post.");

        $ids = [];

        if($pass["ids"]) {

            foreach ($pass["ids"] as $k => $v) {
                $ids[] = $v["id"];
            }
            $uid_arr = Db::name("user")->where("order_id", "in", $ids)->where("status","=",5)->column("uid");
//
//            $username = Db::name("user")->where("uid",$uid)->value("username");
//            $openid = Db::name("wx_users")->where("uid",$uid)->value("openid");
//            $time = date("Y-m-d H:i:s",(time()+7200));
//            //$flag   = $params["bank_name"]."-".$params["bank_no"]."-".$params["cash"]."元";
//            $content = [
//                $username,$row["goods_sno"],$time
//            ];
//            $msg = [
//                "condition"=>13,
//                "touser"=>$openid,
//                "content"=>$content
//            ];
//            $MiniMsg = new  \app\common\lib\MiniMsg($msg);
//            $MiniMsg->sendMsg();//发送短信模板催款成功
//            renderJson("成功催付", 1);
        } else{

                renderJson("请勾选你的选项", 0);
            }


    }

    /**
     * 订单完成
     */
    public function text(){

       $gb =  new \app\common\controller\GoldBean();
       $gb->beanDistribution();

    }
}
